const path = require('path');
const baseConfig = require('./webpack.base.js');
const merge = require('webpack-merge');
const webpack = require('webpack');

const DEV_SERVER_CONFIG = {
  HOST: '127.0.0.1',
  PORT: 9003,
  HMR_PATH: '__webpack_hmr',
  TIMEOUT: 20000
};

const hotHttpUrlpart = `http://${DEV_SERVER_CONFIG.HOST}:${DEV_SERVER_CONFIG.PORT}/`;

Object.keys(baseConfig.entry).forEach(v => {
  if (v !== "vendor") {
    baseConfig.entry[v] = [
      baseConfig.entry[v],
      `webpack-hot-middleware/client?path=${hotHttpUrlpart}${DEV_SERVER_CONFIG.HMR_PATH}&timeout=${DEV_SERVER_CONFIG.TIMEOUT}`
    ];
  }
});

const webpackConfig = merge.smart(baseConfig, {
  // 开发环境
  mode: 'development',
  // source-map 开发工具呈现代码映射关系
  devtool:'eval-cheap-module-source-maps',
  // 开发环境output配置
  output: {
    filename: 'js/[name]_[chunkhash:8].bundle.js',
    path: path.join(process.cwd(), './app/public/dist/dev/'),
    publicPath: `${hotHttpUrlpart}public/dist/dev/`, // 外部资源公共路径
    globalObject: 'this',
  },
  // 开发阶段插件
  plugins: [
    // 热更新插件 实现热模块替换
    // 允许在程序运行时替换模块
    // 极大提升开发效率 能让应用程序一直保持运行状态
    new webpack.HotModuleReplacementPlugin({
      multiStep: false
    }),
  ],
  // devServer配置
  devServer: {
    contentBase: path.join(process.cwd(), './app/public/dist/dev/'),
    compress: true,
    port: DEV_SERVER_CONFIG.PORT,
    hot: true,
    publicPath: `${hotHttpUrlpart}public/dist/dev/`,
  }
});

module.exports = {
  // webpack 配置
  webpackConfig,
  // devserver配置暴露给dev.js
  DEV_SERVER_CONFIG
};